package pharmacy.model;

import misc.Utils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import pharmacy.Pharmacy;

import java.io.IOException;
import java.util.Arrays;
import java.util.Vector;

public class Concelho {
    private final String nome;

    private final String href;

    private Concelho(Element element) {
        nome = element.text();
        href = element.attr("href");
    }

    public String getHref() {
        return href;
    }

    public static Vector<Concelho> load(District district) throws IOException {
        try {
            Concelho[] array = Utils.DATA_FOLDER.fromJson(district.getNome(), Concelho[].class);
            return new Vector<>(Arrays.asList(array));
        } catch (Exception e) {
            System.out.println("File doesn't exist. Loading from site...");
            Vector<Concelho> concelhos = new Vector<>();

            String url = Pharmacy.URL + district.getHref();
            Document document = Jsoup.connect(url).get();
            final Elements links = document.select("#barraConcelhos a");
            for (Element link : links)
                concelhos.add(new Concelho(link));

            Utils.DATA_FOLDER.toJson(district.getNome(), concelhos);

            return concelhos;
        }
    }

    @Override
    public String toString() {
        return nome;
    }

    public Farmacias[] getFarmacias() throws IOException {
        return Farmacia.load(this);
    }
}
